package cn.yuhh.api.controller;

import cn.yuhh.api.exception.ApiException;
import cn.yuhh.api.helper.ApiResponse;
import cn.yuhh.api.service.IApiService;
import cn.yuhh.core.type.ResponseHeader;
import cn.yuhh.spring.core.SpringApplicationContext;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ysw
 * @create 2020-02-17 16:18
 * @descreption
 **/
@RestController
@RequestMapping("/")
@Slf4j
public class HttpController {

    @RequestMapping("/api/{service}")
    public Object service(@PathVariable String service, @RequestParam(required = false,defaultValue = "1.0") String version,
                          @RequestParam(required = false,defaultValue = "{}") String data,
                          @RequestHeader(required = false) String sessionId,
                          @RequestParam(required = false,defaultValue = "") String selfId,
                          @RequestParam(value = "file", required = false) MultipartFile[] file,
                          @RequestParam(value = "timestamp") Long timestamp,
                          HttpServletRequest request,
                          HttpServletResponse response
    ){
        Object result = null;
       try {
           log.info("request service :{} ,param:{}",service,data);

           if("systemTime".equals(service)){
               return ApiResponse.success(new HashMap(){{
                   put("time", System.currentTimeMillis() / 1000);
               }});
           }

           Map requestParams = JSON.parseObject(data, HashMap.class);
           requestParams.put("selfId", selfId);
           requestParams.put("sessionId", sessionId);
           requestParams.put("file", file);
           IApiService apiService = SpringApplicationContext.getBean(service+version);
            //判断service是否为空
           if(apiService == null){
               throw new ApiException(ResponseHeader.NOT_SERVICE);
           }
           //验证请求参数
           apiService.validate(requestParams);

           //执行service
           StopWatch stopWatch = new StopWatch();
           stopWatch.start();
           result = apiService.service(requestParams);
           stopWatch.stop();
           log.info("service:[{}{}], total time millis:[{}]", service, version, stopWatch.getTotalTimeMillis());

       }catch (ApiException e){
            log.error("接口{}异常,param={}",service,data,e);
           return ApiResponse.fail(e.getHeader());
       }catch (Exception e){
           log.error("程序异常,{}",data,e);
           return ApiResponse.fail("系统繁忙请联系管理员！");
       }
        return result;

    }
}